package spring.cloud.tasks.executor.listener.analyse;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.common.Service;
import spring.cloud.tasks.executor.task.TaskExecutor;
import spring.cloud.tasks.executor.task.statistics.ProcessCountStatistics;

/**
 * 作业服务器节点统计服务.
 */
@Slf4j
@Setter
@Getter
public class AnalyseService extends Service {

    public AnalyseService(final TaskExecutor taskExecutor) {
        super(taskExecutor);

    }

    @Override
    public void start() {
        super.start();
        initTotalCountDelta();
        initFailureCountDelta();
    }

    private void initTotalCountDelta() {
        // init total count.
        Integer count = 0;
        if (!this.getTaskNodeStorage().isTaskNodeExisted(AnalyseNode.total_count_delta)) {
            this.getTaskNodeStorage().createOrUpdateTaskNodeWithValue(AnalyseNode.total_count_delta, count.toString());
        }
        ProcessCountStatistics.initTotalCountDelta(taskId, executorId, 0);
    }

    public synchronized void persistTotalCountDelta() {
        int delta = ProcessCountStatistics.getTotalCountDelta(taskId, executorId);
        if (delta > 0) {
            int $delta = Integer.parseInt(this.getTaskNodeStorage().getTaskNodeData(AnalyseNode.total_count_delta));
            this.getTaskNodeStorage().updateTaskNode(AnalyseNode.total_count_delta, $delta + delta);
            ProcessCountStatistics.initTotalCountDelta(taskId, executorId, 0);
        }
    }

    private void initFailureCountDelta() {
        // init error count.
        Integer count = 0;
        if (!this.getTaskNodeStorage().isTaskNodeExisted(AnalyseNode.failure_count_delta)) {
            this.getTaskNodeStorage().createOrUpdateTaskNodeWithValue(AnalyseNode.failure_count_delta, count.toString());
        }
        ProcessCountStatistics.initFailureCountDelta(taskId, executorId, 0);
    }

    public synchronized void persistFailureCountDelta() {
        int delta = ProcessCountStatistics.getFailureCountDelta(taskId, executorId);
        if (delta > 0) {
            int $delta = Integer.parseInt(this.getTaskNodeStorage().getTaskNodeData(AnalyseNode.failure_count_delta));
            this.getTaskNodeStorage().updateTaskNode(AnalyseNode.failure_count_delta, delta + $delta);
            ProcessCountStatistics.initFailureCountDelta(taskId, executorId, 0);
        }
    }

}
